﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace SortGUI
{
    // 实现 Bubble Sort 算法
    public class BubbleSort : SortBase
    {

        override public void Sort(int[] alNum)
        {
            //初始化
            Initialize();
            for (int i = 0; i < alNum.Length; i++)
            {
                for (int j = 0; j < alNum.Length - i - 1; j++)
                {
                    lastSwappedIndices[0] = j;
                    lastSwappedIndices[1] = j + 1;
                    if (alNum[j] > alNum[j + 1])
                        Swap(ref alNum[j], ref alNum[j + 1]);

                    // 如果在这一轮内没有发生交换，则说明从当前位置到最后都是已排序的
                    if (!swapped)
                        lastSortedIndex = alNum.Length - i;

                    else
                        // 发生了交换，所以只更新到交换发生的索引
                        lastSortedIndex = Math.Max(lastSortedIndex, lastSwappedIndices[1]);
                    count++;
                    SortNextStep();
                }
            }
            //排序完成
            Complete();
        }

        public override void Initialize()
        {
            count = 0;
            updataColor(isInitialize = false);
        }


        public override void SortNextStep()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex, swapped); // 更新UI
        }

        public override void Complete()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex - 2, swapped);
        }
    }


}


